Security News
Dutch National Police Disrupt Redline and Meta Malware Operations
Dutch National Police and FBI dismantle Redline and Meta infostealer malware-as-a-service operations in Operation Magnus, seizing servers and source code.
urlpattern-polyfill
Advanced tools
The urlpattern-polyfill npm package provides a polyfill for the URLPattern API, which is a web standard for parsing and matching URLs against patterns. It is useful for routing in web applications, validating URLs, and extracting parts of URLs based on a predefined pattern.
Parsing and matching URLs
This feature allows you to define a URL pattern and then match URLs against it. If the URL matches, you can extract parts of it, such as path segments or query parameters.
const pattern = new URLPattern({ pathname: '/books/:id' });
const result = pattern.exec('/books/123');
console.log(result.pathname.groups.id); // '123'
Pattern matching with wildcards and modifiers
This feature enables the use of wildcards (*) and other modifiers to create flexible URL patterns that can match a variety of URL structures.
const pattern = new URLPattern({ pathname: '/books/*' });
const isMatch = pattern.test('/books/sci-fi');
console.log(isMatch); // true
Compatibility with the URLPattern API
The polyfill aims to be compatible with the URLPattern API, providing the same methods and properties that would be available in environments where the API is natively supported.
const pattern = new URLPattern('https://example.com/books/:id');
const isCompatible = 'exec' in pattern && 'test' in pattern;
console.log(isCompatible); // true
path-to-regexp is a popular package for converting paths to regular expressions. It is widely used in Express.js for route pattern matching. Unlike urlpattern-polyfill, which aims to polyfill a specific web standard, path-to-regexp provides a more general solution for path matching and does not conform to the URLPattern API.
route-recognizer is a library for matching paths against defined route patterns. It is designed for use with client-side routers. While it serves a similar purpose to urlpattern-polyfill, it has its own API and does not attempt to polyfill the URLPattern API.
url-pattern is a library that makes it easy to match URLs against patterns. It offers similar functionality to urlpattern-polyfill but does not specifically aim to implement the URLPattern API. Instead, it provides its own set of features and API for pattern matching.
URLPattern is a new web API for matching URLs. Its intended to both provide a convenient API for web developers and to be usable in other web APIs that need to match URLs; e.g. service workers. The explainer discusses the motivating use cases.
This is a polyfill for the URLPattern API so that the feature is available in browsers that don't support it natively. This polyfill passes the same web platform test suite.
The polyfill works in browsers (ESM module) and in Node.js either via import (ESM module) or via require (CJS module).
The polyfill will only be loaded if the URLPattern doesn't already exist on the global object, and in that case it will add it to the global object.
// Conditional ESM module loading (Node.js and browser)
// @ts-ignore: Property 'UrlPattern' does not exist
if (!globalThis.URLPattern) {
await import("urlpattern-polyfill");
}
/**
* The above is the recommended way to load the ESM module, as it only
* loads it on demand, thus when not natively supported by the runtime or
* already polyfilled.
*/
import "urlpattern-polyfill";
/**
* In case you want to replace an existing implementation with the polyfill:
*/
import {URLPattern} from "urlpattern-polyfill";
globalThis.URLPattern = URLPattern
Note:
The line with
// @ts-ignore: Property 'UrlPattern' does not exist
is needed in some environments because before you load the polyfill it might not be available, and the feature-check in the if statement gives an TypeScript error. The whole idea is that it loads when its not there.
// Conditional CJS module loading (Node.js)
if (!globalThis.URLPattern) {
require("urlpattern-polyfill");
}
/**
* The above is the recommended way to load the CommonJs module, as it only
* loads it on demand, thus when not natively supported by the runtime or
* already polyfilled.
*/
require("urlpattern-polyfill");
/**
* In case you want to replace an existing implementation with the polyfill:
*/
const {URLPattern} = require("urlpattern-polyfill");;
globalThis.URLPattern = URLPattern
Note:
No matter how you load the polyfill, when there is no implementation in your environment, it will always add it to the global object.
let p = new URLPattern({ pathname: '/foo/:name' });
let r = p.exec('https://example.com/foo/bar');
console.log(r.pathname.input); // "/foo/bar"
console.log(r.pathname.groups.name); // "bar"
let r2 = p.exec({ pathname: '/foo/baz' });
console.log(r2.pathname.groups.name); // "baz"
// Match same-origin jpg or png URLs.
// Note: This uses a named group to make it easier to access
// the result later.
const p = new URLPattern({
pathname: '/*.:filetype(jpg|png)',
baseURL: self.location
});
for (let url in url_list) {
const r = p.exec(url);
// skip non-matches
if (!r) {
continue;
}
if (r.pathname.groups['filetype'] === 'jpg') {
// process jpg
} else if (r.pathname.groups['filetype'] === 'png') {
// process png
}
}
The pattern in this case can be made simpler without the origin check by leaving off the baseURL.
// Match any URL ending with 'jpg' or 'png'.
const p = new URLPattern({ pathname: '/*.:filetype(jpg|png)' });
We are planning to also support a "short form" for initializing URLPattern objects. This is supported by the polyfill but not yet by the Chromium implementation.
For example:
const p = new URLPattern("https://*.example.com/foo/*");
Or:
const p = new URLPattern("foo/*", self.location);
API overview with typeScript type annotations is found below. Associated browser Web IDL can be found here.
type URLPatternInput = URLPatternInit | string;
class URLPattern {
constructor(init?: URLPatternInput, baseURL?: string);
test(input?: URLPatternInput, baseURL?: string): boolean;
exec(input?: URLPatternInput, baseURL?: string): URLPatternResult | null;
readonly protocol: string;
readonly username: string;
readonly password: string;
readonly hostname: string;
readonly port: string;
readonly pathname: string;
readonly search: string;
readonly hash: string;
}
interface URLPatternInit {
baseURL?: string;
username?: string;
password?: string;
protocol?: string;
hostname?: string;
port?: string;
pathname?: string;
search?: string;
hash?: string;
}
interface URLPatternResult {
inputs: [URLPatternInput];
protocol: URLPatternComponentResult;
username: URLPatternComponentResult;
password: URLPatternComponentResult;
hostname: URLPatternComponentResult;
port: URLPatternComponentResult;
pathname: URLPatternComponentResult;
search: URLPatternComponentResult;
hash: URLPatternComponentResult;
}
interface URLPatternComponentResult {
input: string;
groups: {
[key: string]: string | undefined;
};
}
The pattern syntax here is based on what is used in the popular path-to-regexp library.
"/"
character.":"
character and then a name. For example, "/:foo/:bar"
has two named groups."/:foo(.*)"
will override the default of matching to the next divider."?"
, "*"
, or "+"
functions just as they do in regular expressions. When a group is optional or repeated and it's preceded by a divider then the divider is also optional or repeated. For example, "/foo/:bar?"
will match "/foo"
, "/foo/"
, or "/foo/baz"
. Escaping the divider will make it required instead."(.*)"
(so-called unnamed groups).Currently we plan to have these known differences with path-to-regexp:
URLs have a canonical form that is based on ASCII, meaning that internationalized domain names (hostnames) also have a canonical ASCII based representation, and that other components such as hash
, search
and pathname
are encoded using percent encoding.
Currently URLPattern
does not perform any encoding or normalization of the patterns. So a developer would need to URL encode unicode characters before passing the pattern into the constructor. Similarly, the constructor does not do things like flattening pathnames such as /foo/../bar to /bar. Currently the pattern must be written to target canonical URL output manually.
It does, however, perform these operations for test()
and exec()
input.
Encoding components can easily be done manually, but do not encoding the pattern syntax:
encodeURIComponent("?q=æøå")
// "%3Fq%3D%C3%A6%C3%B8%C3%A5"
new URL("https://ølerlækkernårdetermit.dk").hostname
// "xn--lerlkkernrdetermit-dubo78a.dk"
If you have information about a security issue or vulnerability with an Intel-maintained open source project on https://github.com/intel, please send an e-mail to secure@intel.com. Encrypt sensitive information using our PGP public key. For issues related to Intel products, please visit https://security-center.intel.com.
FAQs
Polyfill for the URLPattern API
The npm package urlpattern-polyfill receives a total of 7,623,550 weekly downloads. As such, urlpattern-polyfill popularity was classified as popular.
We found that urlpattern-polyfill demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Dutch National Police and FBI dismantle Redline and Meta infostealer malware-as-a-service operations in Operation Magnus, seizing servers and source code.
Research
Security News
Socket is tracking a new trend where malicious actors are now exploiting the popularity of LLM research to spread malware through seemingly useful open source packages.
Security News
Research
Noxia, a new dark web bulletproof host, offers dirt cheap servers for Python, Node.js, Go, and Rust, enabling cybercriminals to distribute malware and execute supply chain attacks.